package ar.com.framenet.base.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.springframework.stereotype.Repository;

@Repository
@SuppressWarnings({ "rawtypes" })
public class SimpleHibernateDAO extends BaseDAO {

	private Class persistentClass;

	@PersistenceContext
	private EntityManager entityManager;

	public void setPersistentClass(Class persistentClass) {
		this.persistentClass = persistentClass;
	}

	public void setPersistentClass(String persistentClass) {
		Class entity = Object.class;
		try {
			entity = Class.forName(persistentClass);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		this.persistentClass = entity;
	}

	public List findAll() {
		return findByCriteria();
	}

	/**
	 * Use this inside subclasses as a convenience method.
	 */
	public List findByCriteria(final Criterion... criterion) {
		return findByCriteria(-1, -1, criterion);
	}

	/**
	 * Use this inside subclasses as a convenience method.
	 */
	protected List findByCriteria(final int firstResult, final int maxResults, final Criterion... criterion) {
		Session session = (Session) entityManager.getDelegate();
		Criteria crit = session.createCriteria(persistentClass);

		for (final Criterion c : criterion) {
			crit.add(c);
		}

		if (firstResult > 0) {
			crit.setFirstResult(firstResult);
		}

		if (maxResults > 0) {
			crit.setMaxResults(maxResults);
		}

		final List result = crit.list();
		return result;
	}

	public void delete(Object entity) {
		entityManager.remove(entityManager.merge(entity));
	}

	public Object save(Object entity) {
		return entityManager.merge(entity);
	}

}
